package com.cdtu.outtake.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.outtake.dao.CommentMapper;
import com.cdtu.outtake.dto.CommentDDto;
import com.cdtu.outtake.dto.CommentDto;
import com.cdtu.outtake.MyException;
import com.cdtu.outtake.controller.vo.CommentVO;
import com.cdtu.outtake.domain.Comment;
import com.cdtu.outtake.domain.Shop;
import com.cdtu.outtake.service.ICommentService;
import com.cdtu.outtake.service.IShopService;
import com.cdtu.outtake.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : shl
 * @Date 2024/4/11 15:30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements ICommentService {

    private final IUserService userService;
    private final IShopService shopService;

    @Override
    public Boolean hasCommentByOrderId(Long orderId) {
        return !CollectionUtils.isEmpty(baseMapper.selectList(new QueryWrapper<Comment>().eq("order_id", orderId)));
    }

    @Override
    public void createComment(CommentVO comment) {
        Comment commentEntity = Comment.builder()
                .orderId(comment.getOrderId())
                .shopId(comment.getShopId())
                .createTime(LocalDate.now())
                .content(comment.getContent())
                .allScore(comment.getAllRate().byteValue())
                .wrapScore(comment.getWrapRate().byteValue())
                .tasteScore(comment.getTasteRate().byteValue())
                .anon(comment.getAnon())
                .photos(comment.getPhotos())
                .userId(userService.getMyUserId())
                .build();
        baseMapper.insert(commentEntity);
    }

    @Override
    public List<CommentDto> getMyComments() {
        return baseMapper.selectList(new QueryWrapper<Comment>().eq("user_id", userService.getMyUserId())).stream()
                .sorted((a, b) -> a.getCreateTime().isAfter(b.getCreateTime()) ? -1 : 1)
                .map(comment -> {
                    Shop shop = shopService.getShopById(comment.getShopId());
                    return CommentDto.builder()
                            .shopName(shop.getName())
                            .shopPicture(shop.getPicture())
                            .id(comment.getId())
                            .allRate(comment.getAllScore())
                            .tasteRate(comment.getTasteScore())
                            .wrapRate(comment.getWrapScore())
                            .photos(comment.getPhotos() != null ? Arrays.stream(comment.getPhotos().split("@")).distinct().collect(Collectors.toList()) : null)
                            .createTime(comment.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy.MM.dd")))
                            .content(comment.getContent())
                            .build();
                })
                .collect(Collectors.toList());
    }

    //TODO 获取商铺评论
    @Override
    public CommentDDto getShopComments(Long id) {
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Comment::getShopId, id).orderByDesc(Comment::getCreateTime);
        List<Comment> comments = baseMapper.selectList(lqw);
        CommentDDto ddto = new CommentDDto();
        ddto.setComments(comments);
        Double tasteCollect = comments.stream().collect(Collectors.averagingDouble(Comment::getTasteScore));
        Double psCollect = comments.stream().collect(Collectors.averagingDouble(Comment::getWrapScore));
        ddto.setShopAvgScore(tasteCollect);
        ddto.setShopPsScore(psCollect);
        return ddto;
    }

    @Override
    public void deleteById(Long id) {
        if (userService.getMyUserId().equals(baseMapper.selectById(id).getUserId())) {
            baseMapper.deleteById(id);
        } else {
            throw new MyException("删除评论失败（无对应权限）");
        }
    }
}
